/*
 * File Name:               XRPCCallbackManager.cs
 * 
 * Description:             简易的本地rpc回调处理方案
 * *                        TType 建议使用枚举类型
 * *                        回调仅能处理同步消息 如果遇到异步消息可以创建两个消息类型来处理
 * Author:                  lisiyu <576603306@qq.com>
 * Create Date:             2016/12/03
 */

using System;
using System.Collections.Generic;

public class XRPCCallbackManager<TType>
    where TType : struct
{
    private Dictionary<TType, Action<object[]>> mActionCallbacks;
    private Dictionary<TType, Func<object[], object[]>> mFuncCallbacks;

    public XRPCCallbackManager()
    {
        mActionCallbacks = new Dictionary<TType, Action<object[]>>();
        mFuncCallbacks = new Dictionary<TType, Func<object[], object[]>>();
    }

    public void requestAction(TType msgType, params object[] args)
    {
        if (mActionCallbacks.ContainsKey(msgType))
            mActionCallbacks[msgType](args);
    }

    public object[] requestFunc(TType msgType, params object[] args)
    {
        if (mFuncCallbacks.ContainsKey(msgType))
            return mFuncCallbacks[msgType](args);
        return null;
    }

    public void registerAction(TType msgType, Action<object[]> callback)
    {
        if (mActionCallbacks.ContainsKey(msgType))
            mActionCallbacks[msgType] += callback;
        else
            mActionCallbacks.Add(msgType, callback);
    }

    public void unRegisterAction(TType msgType, Action<object[]> callback)
    {
        if (mActionCallbacks.ContainsKey(msgType))
        {
            mActionCallbacks[msgType] -= callback;
            if (mActionCallbacks[msgType] == null)
                mActionCallbacks.Remove(msgType);
        }
    }

    public void registerFunc(TType msgType, Func<object[], object[]> callback)
    {
        if (mFuncCallbacks.ContainsKey(msgType))
            mFuncCallbacks[msgType] = callback;
        else
            mFuncCallbacks.Add(msgType, callback);
    }

    public void unRegisterFunc(TType msgType, Func<object[], object[]> callback)
    {
        if (mFuncCallbacks.ContainsKey(msgType))
        {
            mFuncCallbacks[msgType] -= callback;
            if (mFuncCallbacks[msgType] == null)
                mFuncCallbacks.Remove(msgType);
        }
    }

    public void clear()
    {
        mActionCallbacks.Clear();
        mFuncCallbacks.Clear();
    }
}
